# -*- coding: utf-8 -*-
 
import pymongo
from pymongo import Connection   
from pymongo.objectid import ObjectId as _id 
import time    
 
class StockView:    
    def __init__(self,db):
        self.db = db
        self.stocks = self.load_stocks()
    def load_stocks(self):
        stocks = []
        for stock in self.db.stocks.find():
            stocks.append(stock)
        return stocks
    
    def prefix_match(self,prefix):
        res = []
        count = 0
        prefix = prefix.lower()
        for s in self.stocks:
            if s['code'].find(prefix)!=-1 or s['spell'].lower().find(prefix)!=-1:
                res.append(s)
                count +=1
                if count>=10: break; 
        return res
    
    def add_fav(self,username,code):
        stock = self.db.stocks.find_one({'code':code})
        if not stock: return
        stk={
            'code': code,
            'name': stock['name'],
            'view_order': 0,
            'fav_date': time.time(),
        }
        exists = self.db.users.find_one({'name':username,'stk_fav.code':code})
        if exists: return'exists'
        self.db.users.update({'name':username},{'$addToSet':{'stk_fav':stk}})
        return stk
    
    def remove_fav(self,username,code):
        self.db.users.update({'name':username},{'$pull':{'stk_fav':{'code':code}}})
        
        